package com.dnzx.auth;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Service;

import com.dnzx.security.JWTUserDetails;
import com.dnzx.util.JwtTokenUtil;

@Service
public class AuthenticatService {

    private static final Logger LOGGER = LoggerFactory.getLogger(AuthenticatService.class);
    @Autowired
    private AuthenticationManager myAuthenticationManager;
    @Autowired
    private UserDetailsService userDetailsService;
    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Value("${jwt.tokenHead}")
    private String tokenHead;

    @Autowired
    public AuthenticatService(AuthenticationManager myAuthenticationManager, UserDetailsService userDetailsService, JwtTokenUtil jwtTokenUtil) {
        this.myAuthenticationManager = myAuthenticationManager;
        this.userDetailsService = userDetailsService;
        this.jwtTokenUtil = jwtTokenUtil;
    }

    public String login(String username, String password) throws Exception {
        try{
            UsernamePasswordAuthenticationToken upToken = new UsernamePasswordAuthenticationToken(username, password);
            final Authentication authentication = myAuthenticationManager.authenticate(upToken);
            SecurityContextHolder.getContext().setAuthentication(authentication);
        }catch (Exception e){
            LOGGER.error(e.getMessage());
            e.printStackTrace();
            throw new Exception("账户或密码错误");
        }

        final JWTUserDetails userDetails = (JWTUserDetails)userDetailsService.loadUserByUsername(username);
        final String token = jwtTokenUtil.generateToken(userDetails);
        return token;
    }

}
